﻿<!DOCTYPE html>
<html>
<head>
    <title>SSE Chat Room with Channels</title>
</head>
<body>
<div id="messages"></div>
<form id="chatForm">
    <select id="channelSelect">
        <!-- 动态填充频道选项 -->
        <option value="1001">1001</option>
        <option value="1002">1002</option>
        <option value="1003">1003</option>
        <option value="2001">2001</option>
        <option value="2002">2002</option>
    </select>
    <input type="text" id="messageInput" placeholder="Type a message..." />
    <button type="submit">Send</button>
</form>

<script type="text/javascript">
    const messagesDiv = document.getElementById('messages');
    const channelSelect = document.getElementById('channelSelect');

    // 获取所有频道并填充下拉菜单
    fetch('/channels')
        .then(response => response.json())
        .then(channels => {
            channels.forEach(channel => {
                let option = document.createElement('option');
                option.value = channel;
                option.textContent = channel;
                channelSelect.appendChild(option);
            });

            // 默认选择第一个频道
            if (channels.length > 0) {
                channelSelect.value = channels[0];
                connectToChannel(channels[0]);
            }
        });

    function connectToChannel(channel) {
        const eventSource = new EventSource(`/stream/${channel}`);
        eventSource.onmessage = function(event) {
            const newMessage = document.createElement('div');
            newMessage.textContent = event.data;
            messagesDiv.appendChild(newMessage);
        };
    }

    document.getElementById('chatForm').addEventListener('submit', function(event) {
        event.preventDefault();
        const messageInput = document.getElementById('messageInput');
        const selectedChannel = channelSelect.value;

        fetch(`/broadcast/${selectedChannel}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(messageInput.value)
        }).then(response => {
            if (response.ok) {
                messageInput.value = '';
            }
        });
    });

    // 监听频道变化事件
    channelSelect.addEventListener('change', function(event) {
        connectToChannel(event.target.value);
    });
</script>
</body>
</html>